package ru.gr.alphaversion;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.zxing.client.android.CaptureActivity;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class Finder extends ActivityGroup implements OnClickListener {
    /** Called when the activity is first created. */
    
	private EditText itemIdForSearch;
	public static final int QRS_ID = 225225;
	public static String id_item, price_item, desc, qua_item, fot_item;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.finder);
        
        itemIdForSearch = (EditText)findViewById(R.id.itemIdForSearch);
            /* InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
       // if (imm != null) {
            imm.showSoftInput(itemIdForSearch, DEFAULT_KEYS_DIALER);
       // }*/
        View findButton = findViewById(R.id.findButton);
        findButton.setOnClickListener(this);
        View findNameButton1 =  findViewById(R.id.findNameButton);
        
        findNameButton1.setOnClickListener(this);
        
        View findButtonQR = findViewById(R.id.findButtonQR);
        findButtonQR.setOnClickListener(this);
        
        
       // Toast.makeText(this, Main.list_id, Toast.LENGTH_LONG).show();
        if(ItemDescription.act==null)
        	ItemDescription.act="0";
		if(ItemDescription.act=="1") {
		Main.checkk = 2;
		}
		if(ItemDescription.act=="3") {
			Main.checkk = 3;
			}
    }
	
    
    public void onClick(View v) {
    	switch (v.getId()) {
    	case R.id.findButton:
    			//Intent findItem = new Intent(this, ItemDescription.class);
        		//findItem.putExtra("ItemId", itemIdForSearch.getText().toString());
        		//replaceContentView("ItemDescription", findItem);
        		//findItem.putExtra("ididid"+Integer.toString(Main.pushq), itemIdForSearch.getText().toString());
        		//onActivityResult(QRS_ID,RESULT_OK,findItem.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    		Intent findItem = new Intent(this, Temp.class);
    		findItem.putExtra("ItemId", itemIdForSearch.getText().toString());
    		/*if(Main.checkk!=0){
    			FinderName parentActivity = (FinderName)getParent();
    			parentActivity.startActivityForResult(findItem, QRS_ID);
    		} else {
    			this.startActivityForResult(findItem, QRS_ID);
    		}*/
    		switch(Main.checkk) {
    		case 1:
    			if(!(ItemDescription.act.equals("1"))||!(ItemDescription.act.equals("3"))){
    			Finder parentActivity = (Finder)getParent();
    			parentActivity.startActivityForResult(findItem, QRS_ID);
    	//		getParent().startActivityForResult(findItemQR, QRS_ID);
    		} else {
    		//case 2:
    	//		FinderName parentActivity1 = (FinderName)getParent();
    			//parentActivity1.
    			startActivityForResult(findItem, QRS_ID);
    		}
    		default:
    			this.startActivityForResult(findItem, QRS_ID);}
    		break;
    		 
    	
    	case R.id.findButtonQR:
    		Intent findItemQR = new Intent(this, CaptureActivity.class);
    		//View view = getLocalActivityManager().startActivity("ItemDescription", findItem.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)).getDecorView(); 
    		//this.setContentView(view);
    		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    		//Toast.makeText(this, Integer.toString(Main.checkk), Toast.LENGTH_LONG).show();
    		if(Main.checkk==1){
    		//switch(Main.checkk) {
    		//case 1:
    			if(ItemDescription.act=="0"){
    			//Finder parentActivity = (Finder)getParent();
    			//parentActivity.
    			startActivityForResult(findItemQR, QRS_ID);
    			}
    			else {
    				startActivityForResult(findItemQR, QRS_ID);
    				ItemDescription.act="0";
    			}
    	//		getParent().startActivityForResult(findItemQR, QRS_ID);
    	
    				} else {
    		//case 2:
    			//FinderName parentActivity1 = (FinderName)getParent();
    			//parentActivity1.
    			//startActivityForResult(findItemQR, QRS_ID);
    		//default:
    			this.startActivityForResult(findItemQR, QRS_ID);
    		}
    		
    		//replaceContentView("ItemDescription", findItemQR);
    		//Toast.makeText(this, "In progress", Toast.LENGTH_LONG).show();
    		break;
    	
    	case R.id.findNameButton:
			//Intent findItem = new Intent(this, ItemDescription.class);
    		//findItem.putExtra("itemName", itemNameForSearch.getText().toString());
    		//replaceContentView("ItemDescription", findItem);
    		//findItem.putExtra("ididid"+Integer.toString(Main.pushq), itemNameForSearch.getText().toString());
    		//onActivityResult(QRS_ID,RESULT_OK,findItem.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    		switch(Main.checkk){
    		
    	case 1:
    	//	Finder parentActivity = (Finder)getParent();
    		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Введите название или его часть");
		// Set an EditText view to get user input
		final EditText input1 = new EditText(this);
		alert.setView(input1);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				//String value = input.getText().toString();
				//Main m = new Main();
				//m.addNameList(value);
							
		Intent findNameItem = new Intent(Finder.this, SearchList.class);
		Log.d("itemname",input1.getText().toString());
		findNameItem.putExtra("ItemName",input1.getText().toString());
		if(Main.checkk == 1){
			if(!ItemDescription.act.equals(1)){
				startActivityForResult(findNameItem, QRS_ID);
			} else {
				if (!ItemDescription.act.equals(2))
				{
			//Finder parentActivity = (Finder)getParent();
			//parentActivity.
			startActivityForResult(findNameItem, QRS_ID);
				}
				else {
					Cats parentActivity = (Cats)getParent();
					parentActivity.startActivityForResult(findNameItem, QRS_ID);
				}
				
			}
		} else {
			//if(ItemDescription.act!="1"){
				Finder.this.startActivityForResult(findNameItem, QRS_ID);
			//} else {
			//FinderName parentActivity = (FinderName)getParent();
			//startActivityForResult(findNameItem, QRS_ID);
			//}
		}
			}});
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		alert.create().show();
    	break;
    	default:
    		//Finder parentActivity = (Finder)getParent();
    		AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
    		
    		alert1.setTitle("Введите название или его часть");
    		// Set an EditText view to get user input
    		final EditText input11 = new EditText(this);
    		alert1.setView(input11);
    		alert1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				//String value = input.getText().toString();
    				//Main m = new Main();
    				//m.addNameList(value);
    							
    		Intent findNameItem = new Intent(Finder.this, SearchList.class);
    		Log.d("itemname",input11.getText().toString());
    		findNameItem.putExtra("ItemName",input11.getText().toString());
    		if(Main.checkk==1){
    			if(ItemDescription.act=="1"){
    				startActivityForResult(findNameItem, QRS_ID);
    			} else {
    			Finder parentActivity = (Finder)getParent();
    			parentActivity.startActivityForResult(findNameItem, QRS_ID);
    			}
    		} else {
    			//if(ItemDescription.act!="1"){
    				startActivityForResult(findNameItem, QRS_ID);
    			//} else {
    			//FinderName parentActivity = (FinderName)getParent();
    			//startActivityForResult(findNameItem, QRS_ID);
    			//}
    		}
    			}});
    		alert1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				// Canceled.
    			}
    		});
    		alert1.create().show();
		
    //		break;
    		break;
    		}
    
    	  default:
    			break;
    	}
  
    	
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	//super.onActivityResult(requestCode, resultCode, data);
    	//Toast.makeText(this, data.getStringExtra("ididid"+Integer.toString(Main.pushq)), Toast.LENGTH_LONG).show();
      // запишем в лог значения requestCode и resultCode
      Log.w("DEBUG", "requestCode = " + requestCode + ", resultCode = " + resultCode);
      //Activity activ = getLocalActivityManager().getCurrentActivity();
      //activ.onActivityResult(requestCode, resultCode, data);
      // если пришло ОК
      if (resultCode == RESULT_OK) {
        switch (requestCode) {
        case QRS_ID:
        //	Activity activity = getLocalActivityManager().getCurrentActivity();
        //    activity.onActivityResult(requestCode, resultCode, data);
        	String ss = data.getStringExtra("ididid"+Integer.toString(Main.pushq));
        	if (ss.indexOf("'") != -1 )
        	{ 
        		ss=ss.substring(1,ss.length()-1);}
        		int a =1;
        	if(isNumeric(ss)) {
        			//Intent findItem_1 = new Intent(this, ItemDescription.class);
        			getDescription(ss);
        			//findItem_1.putExtra("ItemId", ss);
            		//Log.d("asdfghjkkjh", ss);
            		//Finder ff = (Finder)getParent();
            		//replaceContentView("ItemDescription", findItem_1);
        	} else {
        		Toast toast = Toast.makeText(this, "Это не код товара!", 1000);
    			toast.setGravity(Gravity.CENTER, 0, 0);
    			toast.show();
        	}
        
          break;
        }
        // если вернулось не ОК
      } else {
        //Toast.makeText(this, Integer.toString(resultCode), 1000).show();
      }
    }
    
    public void replaceContentView(String id, Intent newIntent) {
    //	View view = getLocalActivityManager().startActivity(id, newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); 
    //	this.setContentView(view);

    		View view = ((ActivityGroup)((Activity)this)).getLocalActivityManager()
    	            .startActivity(id,
    	                    newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
    	            .getDecorView();
        	((ActivityGroup)((Activity)this)).setContentView(view);
    	
    } 
    
    @Override
    public void onBackPressed() {
    	
    }
    
    public static boolean isNumeric(String str)  
    {  
      try  
      {  
        Double.parseDouble(str);  
      }  
      catch(NumberFormatException nfe)  
      {  
        return false;  
      }  
      return true;  
    }
    
    public void getDescription(String ItemId) {
		GetJSON json = new GetJSON();
		try {
			String gg = json.postData(ItemId, "", "QSearchItemById", "", this);
			JSONObject jsonObject = new JSONObject(gg);
			if(gg!="") {
				if(jsonObject.getString("error").equals("1")) {
					Toast toast = Toast.makeText(this, "Нет товара с таким кодом", Toast.LENGTH_LONG);
        			toast.setGravity(Gravity.CENTER, 0, 0);
        			toast.show();
				} else {
					JSONArray jsonArray = new JSONArray(jsonObject.getString("items"));
					JSONObject jsonObject_1 = jsonArray.getJSONObject(0);
					desc = jsonObject_1.getString("NAME");
					//+"\n"+"ID: "+jsonObject_1.getString("ID");
					id_item = jsonObject_1.getString("ID").replaceAll("\\s", " ").trim();
					price_item = jsonObject_1.getString("PRICE");
					qua_item = jsonObject_1.getString("QUANTITY");
					fot_item = jsonObject_1.getString("FOTO");
					Intent findItem_1 = new Intent(this, ItemDescription.class);
					findItem_1.putExtra("ItemId", id_item);
					findItem_1.putExtra("price_item", price_item);
					findItem_1.putExtra("desc", desc);
					findItem_1.putExtra("qua_item", qua_item);
					findItem_1.putExtra("fot_item", fot_item);
					//Log.d("asdfghjkkjh", ss);
					//Finder ff = (Finder)getParent();
					replaceContentView("ItemDescription", findItem_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				}
			} else {
				//Toast.makeText(this, "Нет соединения с сервером", Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}